package cn.wolfcode.wolf2w.gateway.filter;

import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.gateway.util.Md5Util;
import com.alibaba.fastjson.JSON;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

// TODO: 2024/8/13 访问受限就关
//@Component
public class SignFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //http://localhost:3000/api/adv/test2?a=1&b=2&c=3&d=4&sign=5B7560C95DBAB0EF43F1B7D57A3756CE
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        Map<String,Object> map = new HashMap<>();
        for (String key : queryParams.keySet()) {
            if("sign".equals(key)){
                continue;
            }
            String value = queryParams.get(key).get(0);
            map.put(key,value);
        }
        String sign_server = Md5Util.signatures(map);
        String sign_client = queryParams.getFirst("sign");
        //由于只有在info.vue中的测试接口添加了sign签名，其它接口没有签名，所以判断null把没加签名的接口放行
        if(sign_client == null){
            return chain.filter(exchange);
        }
        if(sign_client == null || sign_client.equals(sign_server)){
            long requestTime = Long.valueOf(queryParams.getFirst("timestamp"));
            long now = System.currentTimeMillis();
            if(now - requestTime > 1 * 60 * 1000){
                exchange.getResponse().getHeaders().add("Content-Type","application/json;charset=UTF-8");
                R<Object> r = R.fail(501, "接口访问超时");
                String jsonString = JSON.toJSONString(r);
                byte[] bytes = jsonString.getBytes(StandardCharsets.UTF_8);
                DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
                return exchange.getResponse().writeWith(Mono.just(buffer));
            }
            return chain.filter(exchange);
        }else{
            exchange.getResponse().getHeaders().add("Content-Type","application/json;charset=UTF-8");
            R<Object> r = R.fail(501, "签名失败，请勿修改参数");
            String jsonString = JSON.toJSONString(r);
            byte[] bytes = jsonString.getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            return exchange.getResponse().writeWith(Mono.just(buffer));
        }

    }
}
